package com.fingard.dsp.bank.directbank.ceb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component("CEB01Balance")
public class CEB01Balance extends CEB01Base implements IBalance {
    /**
     * @param p_req7506
     * @return
     * @throws Exception
     */
    //单个余额查询和批量余额查询，统一采用流处理方式
    //1、循环调用Req7506BalQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用RetAts7506BalQry.writeRetDetail()，写入返回ATS的明细
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {//余额查询
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CEB01Header bankHeader = new CEB01Header();
            bankHeader.batchID = this.getBatchID();
            bankHeader.requestCode = "balance";
            bankHeader.transNodeName = "balance";
            bankHeader.transPatches = String.valueOf(p_req7506.detailCount);
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeaderBalTrans(xmlWriter, bankHeader);

            xmlWriter.writeStartElement(bankHeader.transNodeName + "RequestBody");
            int countRd = 0;
            while (p_req7506.readRecord()) {
                if (p_req7506.readedDetail.savingType.equals("3")) {    //保证金账户
                    return d_7506_BailAccountQry(p_req7506);
                }
                countRd++;
                xmlWriter.writeStartElement(bankHeader.transNodeName + "RequestRecord");
                xmlWriter.writeElementString("clientPatchID", bankHeader.batchID + String.format("%04d", countRd));
                xmlWriter.writeElementString("accountNo", p_req7506.readedDetail.actNum);
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), bankHeader.requestCode);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    //"/transaction/"+bankHeader.transactionNodeName+"/"+bankHeader.transactionNodeName+"Respond/"+bankHeader.transactionNodeName+"RespondHeader/respondStatus/respondInfo"
                    String respondCode = tmpBkReader.getSimpleText("respondCode");
                    String respondInfo = tmpBkReader.getSimpleText("respondInfo");
                    if (respondCode != null && respondCode.equals("0000")) {
                        String ndName = bankHeader.transNodeName;
                        while (tmpBkReader.read("/transaction/" + ndName + "/" + ndName + "Respond/" + ndName + "RespondBody/" + ndName + "RespondRecord")) {
                            RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("accountNo");
                            tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("accountBalance");
                            tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("availableBalance");

                            String returnCode = tmpBkReader.readedXElement.getSingleText("returnCode");
                            String returnInfo = tmpBkReader.readedXElement.getSingleText("returnInfo");
                            if (returnCode != null && returnCode.equals("0000")) {
                                tmpRetDetail.respCode = "0";
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = returnInfo;
                            }
                            retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        if (StringHelper.isNullOrEmpty(respondInfo)) {
                            respondInfo = tmpBkReader.getSimpleText("error");
                        }
                        String returnInfo = tmpBkReader.getSimpleText("returnInfo");
                        if (!StringHelper.isNullOrEmpty(returnInfo)) {
                            respondInfo = respondInfo + " " + returnInfo;
                        }
                        retAts.writeRespInfo(respondInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpRetBkStr[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 保证金账户及余额查询，光大第二批接口规范
     *
     * @param p_req7506
     * @return
     */
    public RetAts7506BalQry d_7506_BailAccountQry(Req7506BalQry p_req7506) throws Exception {
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息

        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {

            int totalSum = 0;
            int startPatches = 1;
            boolean queryContinue = true;
            while (queryContinue) {
                CEB01Header bankHeader = new CEB01Header();
                bankHeader.TransCode = "b2e001012"; //交易码，第二批规范
                bankHeader.batchID = getBatchID();  //交易流水号
                bankHeader.JnlDateTime = new Date();//请求日期和时间
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                int countRd = 1;
                writeCommonHeader_2(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("TransContent");
                XElement tmpXElement = new XElement("ReqData", "");
                tmpXElement.addChild(new XElement("ClientPatchID", bankHeader.batchID + String.format("%04d", countRd)));
                tmpXElement.addChild(new XElement("QISHBS", String.valueOf(startPatches)));
                tmpXElement.addChild(new XElement("CXUNBS", "99"));
                xmlWriter.writeXElement(tmpXElement);
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();

                String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                        String respondInfo = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                        if (tmpReturnCode != null && "0000".equals(tmpReturnCode)) {
                            totalSum = tmpBkReader.getFirstText("/Transaction/TransContent/TotalNum").length() == 0 ? 0 : Integer.parseInt(tmpBkReader.getFirstText("/Transaction/TransContent/TotalNum"));
                            while (tmpBkReader.read("/Transaction/TransContent/BatchRespList/RespData")) {
                                RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                                String actNum = tmpBkReader.readedXElement.getSingleText("ZHANGH");
                                if (actNum.equals(p_req7506.readedDetail.actNum)) {
                                    tmpRetDetail.actNum = actNum;
                                    tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("ZHHUYE");
                                    tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("HUOBDH"));
                                    retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                                    queryContinue = false;
                                    tmpRespCode = "0";
                                    tmpRespInfo = "SUCCESS";
                                    break;
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "没有查询到指定账户的信息" + "[" + actNum + "]";
                                }
                            }
                            startPatches += 99;
                            if (!(startPatches < totalSum && totalSum != 0 && (totalSum > 99))) {
                                queryContinue = false;
                            }
                        } else {
                            tmpRespCode = "-1";
                            String returnInfo = tmpBkReader.getFirstText("/transaction/error");
                            tmpRespInfo = returnInfo;
                            queryContinue = false;
                        }
                    } else {
                        queryContinue = false;
                        tmpRespCode = "-1";
                        ;
                        tmpRespInfo = tmpSbMsg.toString();
                    }
                } else {
                    queryContinue = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRespCode(tmpRespCode);
        retAts.writeRespInfo(tmpRespInfo);
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {

            int totalSum = 0;
//            int startPatches = 1;
            boolean queryContinue = true;
            while (queryContinue) {
                CEB01Header bankHeader = new CEB01Header();
                bankHeader.TransCode = "b2e001014"; //交易码，第二批规范
                bankHeader.batchID = getBatchID();  //交易流水号
                bankHeader.JnlDateTime = new Date();//请求日期和时间
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                int countRd = 1;
                writeCommonHeader_2(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("TransContent");
                XElement tmpXElement = new XElement("ReqData", "");
                tmpXElement.addChild(new XElement("ClientPatchID", bankHeader.batchID + String.format("%04d", countRd)));
                tmpXElement.addChild(new XElement("CXAcNo", p_req7505.actNum));
                tmpXElement.addChild(new XElement("startTime", Format.Date8Format.format(p_req7505.getDateFrom())));
                tmpXElement.addChild(new XElement("endTime", Format.Date8Format.format(p_req7505.getDateTo())));
                xmlWriter.writeXElement(tmpXElement);
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();

                String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                        String respondInfo = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                        if (tmpReturnCode != null && "0000".equals(tmpReturnCode)) {
//                            totalSum = tmpBkReader.getFirstText("/Transaction/TransContent/TotalNum").length() == 0 ? 0 : Integer.parseInt(tmpBkReader.getFirstText("/Transaction/TransContent/TotalNum"));
                            while (tmpBkReader.read("/Transaction/TransContent/BatchRespList/RespData")) {
                                RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                                String actNum = tmpBkReader.readedXElement.getSingleText("AcNo");
                                if (actNum.equals(p_req7505.actNum)) {
                                    tmpRetDetail.balDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("date"));
                                    tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleText("balance");
                                    tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("availableBalance");
                                    retAts.writeRetDetail(tmpRetDetail);
                                    queryContinue = false;
                                    tmpRespCode = "0";
                                    tmpRespInfo = "SUCCESS";
                                    break;
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "没有查询到指定账户的信息" + "[" + actNum + "]";
                                }
                            }
//                            startPatches += 99;
//                            if (!(startPatches < totalSum && totalSum != 0 && (totalSum > 99))) {
//                                queryContinue = false;
//                            }
                        } else {
                            tmpRespCode = "-1";
                            String returnInfo = tmpBkReader.getFirstText("/transaction/error");
                            tmpRespInfo = returnInfo;
                            queryContinue = false;
                        }
                    } else {
                        queryContinue = false;
                        tmpRespCode = "-1";
                        ;
                        tmpRespInfo = tmpSbMsg.toString();
                    }
                } else {
                    queryContinue = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRespCode(tmpRespCode);
        retAts.writeRespInfo(tmpRespInfo);
        retAts.writeEnd();
        return retAts;
    }

}
